package me.chan.mongo;

import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.gt;

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;
import org.bson.types.ObjectId;

import com.mongodb.BasicDBObject;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

public class MongoCrudDemo {

	public static void main(String[] args) {
		String url = "127.0.0.1";
		int port = 27017;
		try  (MongoClient connection = new MongoClient(url, port)) {
				MongoDatabase db = connection.getDatabase("mongo");
				MongoCollection<Document> collection = db.getCollection("fruit");
				FindIterable<Document> docIterator = collection.find();
				Document doc = docIterator.filter(eq("weight", 100)).first();
				System.out.println(doc);
				
				Block<Document> printBlock =  new Block<Document>() {
					@Override
					public void apply(Document t) {
						System.out.println(t.toJson());
					}
				};
				// find all apples of which attribute weight  are greater than 100 
				collection.find(gt("weight", 100)).forEach(printBlock);
	
				//iteration
				MongoCursor<Document> cursor = collection.find().iterator();
				while(cursor.hasNext()) {
					System.out.println(cursor.next().toJson());
				}
				
				List<Document> docs = new ArrayList<>();
				//add multi
				for (int i=0; i<10; ++i) {
					docs.add(new Document("i"+i, i));
				}
				collection.insertMany(docs);
				
				BasicDBObject dbObj = new BasicDBObject();
				dbObj.put("weight", 250);
				dbObj.put("name", "theNewestApple");
				dbObj.put("color", "orange");
				dbObj.put("_id", new ObjectId());
				Document document = new Document(dbObj);
				collection.insertOne(document);
				
				//update
				collection.updateOne(eq("name" ,"theNewestApple"), 
						new Document("$set", new Document("color","red")));
				
				//delete
				collection.deleteOne(eq("_id", new ObjectId("58fe261f3ef34b1ce67ff1de")));
			} catch(Exception ex) {
				ex.printStackTrace();
			} 
		}
}
